<template>
  <div class="user-management">
    <div class="header">
      <h2>客户账号管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="searchForm.company_name" placeholder="请输入公司名称" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="searchForm.phone_number" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 100px;" clearable>
            <el-option label="正常" value="active" />
            <el-option label="已冻结" value="frozen" />
            <el-option label="待审核" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 客户列表 -->
    <el-table :data="userList" style="width: 100%" border>
      <el-table-column prop="userId" label="客户ID" width="100" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="companyName" label="公司名称" width="180" />
      <el-table-column prop="phoneNumber" label="联系电话" width="150" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button
            v-if="scope.row.status !== 'pending'"
            :type="scope.row.status === 'frozen' ? 'success' : 'warning'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 'frozen' ? '解冻' : '冻结' }}
          </el-button>
          <el-button
            v-if="scope.row.status === 'pending'"
            type="success"
            size="small"
            @click="handleApprove(scope.row)"
          >
            审核通过
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, reactive,onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUsers,updateUserStatus } from '../../api/userApi'

export default {
  name: 'UserManagement',
  setup() {
    const userList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const searchForm = reactive({
      name: '',
      company_name: '',
      phone_number: '',
      status: ''
    })
    const nowSearchForm = reactive({
      name: '',
      companyName: '',
      phoneNumber: '',
      status: '',
    })

    onMounted(()=>{
      getUserList()
    })

    // 获取客户列表
    const getUserList = async () => {
      try {
        const params = {
          name: nowSearchForm.name,
          companyName: nowSearchForm.companyName,
          phoneNumber: nowSearchForm.phoneNumber,
          status: nowSearchForm.status,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        console.log(params);
        const res = await getUsers(params)
        console.log(res);
        if(res.flag){
          userList.value = res.result.records
          total.value = res.result.total
        }        

      } catch (error) {
        ElMessage.error('获取客户列表失败')
      }
    }

    // 状态类型
    const getStatusType = (status) => {
      const types = {
        active: 'success',
        frozen: 'danger',
        pending: 'warning'
      }
      return types[status] || 'info'
    }

    // 状态文本
    const getStatusText = (status) => {
      const texts = {
        active: '正常',
        frozen: '已冻结',
        pending: '待审核'
      }
      return texts[status] || status
    }

    // 处理搜索
    const handleSearch = () => {
      nowSearchForm.name = searchForm.name
      nowSearchForm.companyName = searchForm.company_name
      nowSearchForm.phoneNumber = searchForm.phone_number
      nowSearchForm.status = searchForm.status
      getUserList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      Object.keys(nowSearchForm).forEach(key => {
        nowSearchForm[key] = ''
      })
      currentPage.value = 1
      pageSize.value = 10
      getUserList()
    }

    // 处理状态变更
    const handleStatusChange = async (row) => {
      let newStatus = ""
      if(row.status === 'pending'){
        newStatus = "active"
      }else if(row.status === 'active'){
        newStatus = "frozen"
      }else if(row.status === 'frozen'){
        newStatus = "active"
      }
      try {
        const res = await updateUserStatus({
          id: row.userId,
          status: newStatus
        }) 
        console.log(res);
        if(res.flag){
          ElMessage.success('状态更新成功')
          getUserList()
        }else{
          ElMessage.error(res.reason)
        }
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    // 处理审核
    const handleApprove = async (row) => {
      try {
        const res = await updateUserStatus({
          id: row.userId,
          status: "active"
        }) 
        console.log(res);
        if(res.flag){
          ElMessage.success('状态更新成功')
          getUserList()
        }else{
          ElMessage.error(res.reason)
        }
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      nowSearchForm.pageSize = val
      getUserList()
    }

    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getUserList()
    }

    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    return {
      userList,
      currentPage,
      pageSize,
      total,
      searchForm,
      getStatusType,
      getStatusText,
      handleSearch,
      resetSearch,
      handleStatusChange,
      handleApprove,
      handleSizeChange,
      handleCurrentChange,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  font-size: 24px;
  color: #1e3c72;
  font-weight: 600;
  margin: 0;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 24px;
  padding: 24px;
  background: #f5f7fa;
  border-radius: 8px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #1e3c72;
  font-weight: 600;
  font-size: 14px;
  height: 50px;
}

:deep(.el-table td) {
  padding: 12px 0;
  font-size: 14px;
}

:deep(.el-table--striped .el-table__row--striped td) {
  background: #f9fafc;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: #1e3c72;
  border-color: #1e3c72;
}

:deep(.el-button--primary:hover) {
  background: #2a5298;
  border-color: #2a5298;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(30, 60, 114, 0.2);
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 4px 8px;
  font-weight: 500;
}

/* 分页样式 */
.pagination {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-pagination) {
  justify-content: flex-end;
  padding: 0;
}

:deep(.el-pagination button) {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-pagination .el-pager li) {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 4px;
  min-width: 32px;
}

:deep(.el-pagination .el-pager li.active) {
  background-color: #1e3c72;
  border-color: #1e3c72;
  color: #ffffff;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #1e3c72;
}

:deep(.el-input) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: #1e3c72;
}

/* 操作按钮组样式 */
:deep(.el-table .cell .el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-table .cell .el-button) {
  padding: 6px 12px;
  font-size: 13px;
}
</style>